package com.sam.im.heiqun.uis.activities;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.RequestRefereeEntity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.NoticeGroupAdapter;
import com.sam.im.heiqun.uis.beans.GetNoticeListEntity;
import com.sam.im.heiqun.uis.beans.NoticeBean;
import com.sam.im.heiqun.uis.beans.RechargeOrderBean;
import com.sam.im.heiqun.utils.MyDialog;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.sam.im.heiqun.view.PullToRefreshListener;
import com.sam.im.heiqun.view.PullToRefreshRecyclerView;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import butterknife.OnClick;

/**
 * Created by wangguodong on 2017/8/17.
 */

public class GroupNoticeListActivity extends BaseSwipeBackActivity implements PullToRefreshListener {

    private static final String TAG = "GroupNoticeListActivity";
    private PullToRefreshRecyclerView NoticeRecycler;

    private String groupId ;

    private List<NoticeBean> mList = new ArrayList<>();
    private NoticeGroupAdapter mAdapter ;

    private ImageView right ;
    private ImageView pre_v_back ;
    private int pageNo = 0 ;
    private String editable ;

    public static void startActivity(Activity activity, String groupId){
        Intent intent = new Intent(activity,GroupNoticeListActivity.class);
        intent.putExtra("groupId",groupId);
        activity.startActivity(intent);
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.group_notice);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {

        groupId = getIntent().getStringExtra("groupId");
        Log.i(TAG, "initViews: -----收到的群组ID----groupId="+groupId);

        NoticeRecycler = (PullToRefreshRecyclerView) findViewById(R.id.pulltorefreshrecyclerview);
        NoticeRecycler.setPullRefreshEnabled(false);
        NoticeRecycler.setLoadingMoreEnabled(false);
        NoticeRecycler.setPullToRefreshListener(this);
        NoticeRecycler.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new NoticeGroupAdapter(GroupNoticeListActivity.this,mList);
        mAdapter.setOnClickListener(new NoticeGroupAdapter.OnClickListener() {
            @Override
            public void OnClick(NoticeBean noticeBean) {
                if ("1".equals(editable)){
                    GroupNoticeEditActivity.startActivity(GroupNoticeListActivity.this,groupId,1,noticeBean);
                }else {
                    GroupNoticeEditActivity.startActivity(GroupNoticeListActivity.this,groupId,2,noticeBean);
                }
            }
        });
        NoticeRecycler.setAdapter(mAdapter);

        mAdapter.setOnLongClickListener(new NoticeGroupAdapter.OnLongClickListener() {
            @Override
            public void OnLongClick(final NoticeBean noticeBean) {
                // 创建构建器
                AlertDialog.Builder builder = new AlertDialog.Builder(GroupNoticeListActivity.this);
                // 设置参数
                builder.setTitle(getResources().getString(R.string.tip)).setIcon(R.drawable.logo)
                        .setMessage(getResources().getString(R.string.delete_notice_ok))
                        .setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteGroupNote(noticeBean.getId());
                                dialog.dismiss();
                            }
                        }).setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.create().show();
            }
        });

        right = (ImageView) findViewById(R.id.right);
        right.setBackgroundResource(R.drawable.notice_edit);
//2248//
   //119//118//38
        //17231
//        getNotice();
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what){
                case 0 :
                    try {
                        if ("1".equals(editable)){
                            right.setVisibility(View.VISIBLE);
                        }else {
                            right.setVisibility(View.GONE);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    @Override
    public int getContentViewId() {
        return R.layout.activity_group_notice_list;
    }

    @Override
    protected void onResume() {
        super.onResume();
        pageNo = 0 ;
        getNotice();
    }

    private void getNotice(){

        PGService.getInstance().getNoteList(ToolsUtils.getMyUserId(), groupId, ""+pageNo).subscribe(new AbsAPICallback<GetNoticeListEntity>() {
            @Override
            public void onNext(GetNoticeListEntity noticeEntivity) {//登录成功后，保存用户信息
//   http://123.57.47.19:8080/wmsMobile/chat/getNoteList?userId=17231&groupId=2248&pageNo=0
                if (null != noticeEntivity){
                    try {
                        if (Integer.parseInt(noticeEntivity.getPageNo()) >= Integer.parseInt(noticeEntivity.getTotalPage())){
                            NoticeRecycler.setLoadingMoreEnabled(false);
                        }else {
                            NoticeRecycler.setLoadingMoreEnabled(true);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    editable = noticeEntivity.getEditable();
                    handler.sendEmptyMessage(0);
                    mList.clear();
//                    int start = mList.size();
                    mList.addAll(noticeEntivity.getList());
//                    int end = mList.size();
//                    mAdapter.notifyItemRangeChanged(0, end-1);
                    mAdapter.notifyDataSetChanged();
                }
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                hideProgress();
            }

            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
            }
        });
    }

    /**
     * 删除公告
     */
    private void deleteGroupNote(String noteId){
        showProgress("");
        PGService.getInstance().deleteGroupNote(noteId, groupId, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity noticeEntivity) {//登录成功后，保存用户信息
//   http://123.57.47.19:8080/wmsMobile/chat/getNoteList?userId=17231&groupId=2248&pageNo=0

                showToast(getResources().getString(R.string.delete_success));
                getNotice();

            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                hideProgress();
                showToast(getResources().getString(R.string.delete_fail));
            }

            @Override
            protected void onResultError(ApiException ex) {
                hideProgress();
                showToast(getResources().getString(R.string.delete_fail));
            }
        });
    }

    @OnClick({R.id.right, R.id.pre_v_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.right: {
                GroupNoticeEditActivity.startActivity(GroupNoticeListActivity.this,groupId);
            }
            break;
            case R.id.pre_v_back:
                finish();
                break;
        }
    }

    @Override
    public void onRefresh() {
        pageNo = 0 ;
        getNotice();
    }

    @Override
    public void onLoadMore() {
//        pageNo ++ ;
        getNotice();
    }
}
